package com.sdd.sdr.utils;

import com.alibaba.csp.sentinel.Constants;
import com.alibaba.csp.sentinel.datasource.ReadableDataSource;
import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.csp.sentinel.datasource.nacos.NacosDataSource;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.csp.sentinel.transport.config.TransportConfig;
import com.alibaba.csp.sentinel.transport.heartbeat.client.SimpleHttpClient;
import com.alibaba.csp.sentinel.transport.heartbeat.client.SimpleHttpRequest;
import com.alibaba.csp.sentinel.transport.heartbeat.client.SimpleHttpResponse;
import com.alibaba.csp.sentinel.transport.util.WritableDataSourceRegistry;
import com.alibaba.csp.sentinel.util.TimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.net.InetSocketAddress;
import java.util.*;

/**
 * ClassName: SentinelUtil
 * Description:
 * date: 2020/7/2
 *
 * @author xugaojun
 */
@Component
@Slf4j
public class SentinelUtil {

    @Value("${sentinel.api.port}")
    private String apiPort;
    @Value("${sentinel.project.name}")
    private String projectName;
    @Value("${sentinel.dashboard.server}")
    private String dashboardAddr;
    @Value("${sentinel.nacos.address}")
    private String remoteAddress;
    @Value("${sentinel.rule.namespace}")
    private String nacosNameSpace;
    @Value("${sentinel.group.id}")
    private String groupId;
    @Value("${sentinel.data-id}")
    private String dataId;

    private static final String ALL_SCOPE_DATA_ID = "sentinel_dynamic_demo_allscope";
    private static final String ALL_SCOPE_GROUP_ID = "allscope";


    @PostConstruct
    private void initProperties() throws NacosException {

        System.setProperty("java.net.perferIPv4Stack", "true");
        System.setProperty("csp.sentinel.api.port", apiPort);
        System.setProperty("project.name", projectName);
        System.setProperty("csp.sentinel.dashboard.server", dashboardAddr);

        sendBasicRule();
        loadNamespaceRules();
        registerWriteableDatasource();
//        sendRegisterMachineHeartBeat2DashBoard();

    }

    /**
     * 推送全局基础规则
     * 因为需要有一个整体
     * @throws NacosException
     */
    private void sendBasicRule() throws NacosException {
        // 构造类级别的规则
        List<FlowRule> rules = new ArrayList<>();
        FlowRule flowRule = new FlowRule();

        flowRule.setResource("com.sdd.sdr.api.UserService");
        flowRule.setControlBehavior(RuleConstant.CONTROL_BEHAVIOR_DEFAULT); // 快速失败
        flowRule.setCount(5);
        flowRule.setLimitApp("sentinel-dynamic-demo");
        flowRule.setStrategy(RuleConstant.STRATEGY_DIRECT);
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);

        rules.add(flowRule);

        String rule = JSON.toJSONString(rules);

        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, remoteAddress);
        properties.setProperty(PropertyKeyConst.NAMESPACE, nacosNameSpace);

        ConfigService configService = NacosFactory.createConfigService(properties);

        // 首次推送 -- 全局性规则
        if (configService.publishConfig(ALL_SCOPE_DATA_ID, ALL_SCOPE_GROUP_ID, rule)) {
            log.info("=====================Nacos:Sentinel[sentinel-dynamic-demo]基础资源推送成功===============================");
        }
    }


    /**
     * 首次加载一遍 全局 类规则 -- 主包名或者主类名
     */
    private void loadNamespaceRules() {
        Properties properties = new Properties();
        properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
        properties.put(PropertyKeyConst.NAMESPACE, nacosNameSpace);

        ReadableDataSource<String, List<FlowRule>> flowRuleDataSource = new NacosDataSource<>(properties, groupId, dataId,
                source -> JSON.parseObject(source, new TypeReference<List<FlowRule>>() {
                }));
        FlowRuleManager.register2Property(flowRuleDataSource.getProperty());
        log.info("=====================Nacos:Sentinel[sentinel-dynamic-demo] 拉取资源配置成功===============================");
    }


    /**
     * 注册写入配置数据源
     */
    private void registerWriteableDatasource() {
        WritableDataSource writableDataSource = new WorktableNacos<List<FlowRule>>();
        WritableDataSourceRegistry.registerFlowDataSource(writableDataSource);
        log.info("=====================Nacos:Sentinel[sentinel-dynamic-demo] 配置中心写入数据源注册成功===============================");
    }


    /**
     * 主动发送一个心跳包到控制台
     */
    private void sendRegisterMachineHeartBeat2DashBoard() {
        if (StringUtils.isEmpty(dashboardAddr)) {
            log.error("===================== 配置错误, 请配置控制台信息 =====================");
            return;
        }
        String[] addrs = dashboardAddr.split(":");
        InetSocketAddress address = new InetSocketAddress(addrs[0], Integer.parseInt(addrs[1]));
        Map<String, String> message = new HashMap<>();

        message.put("v", Constants.SENTINEL_VERSION);
        message.put("version", String.valueOf(TimeUtil.currentTimeMillis()));
        message.put("port", String.valueOf(TransportConfig.getPort()));
        log.info("===================== 发送心跳" + TransportConfig.getPort() + " =====================");

        // 注册机器
        SimpleHttpClient httpClient = new SimpleHttpClient();
        SimpleHttpRequest request = new SimpleHttpRequest(address, TransportConfig.HEARTBEAT_DEFAULT_PATH);
        try {
            for (int i = 0; i < 5; i++) {
                SimpleHttpResponse response = httpClient.post(request);
                if (response.getStatusCode() == 200) {
                    log.info("===================== 发送心跳成功 =====================");
                }
            }

        } catch (Exception e) {
            log.warn("[SimpleHttpHeartbeatSender] Failed to send heartbeat to " + addrs[0], e);
        }
    }


    /**
     * 配置规则写入
     *
     * @param <T>
     */
    class WorktableNacos<T> implements WritableDataSource<T> {

        // 当sentinel update 时候
        @Override
        public void write(T value) throws Exception {
            String s = JSON.toJSONString(value);
            // 发布配置
            Properties properties = new Properties();
            properties.put(PropertyKeyConst.SERVER_ADDR, remoteAddress);
            properties.put(PropertyKeyConst.NAMESPACE, nacosNameSpace); // 指定namespace配置
            ConfigService configService = NacosFactory.createConfigService(properties);
            boolean isPublishOk = configService.publishConfig(dataId, groupId, s);
            log.info("isPublishOk========" + isPublishOk);
        }

        @Override
        public void close() throws Exception {
        }
    }

}
